package com.feilo.main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

public class PPTtoImage {
	public static void main(String[] args) {
		// 读入PPT文件
		PPTtoImage.doPPTtoImage(new File("D:\\temp\\out\\5.ppt"));
		//PPTtoImage.doPPT2007toImage(new File("D:\\temp\\out\\4.pptx"));
		System.out.println("finish");
	}

	public static boolean doPPTtoImage(File file) {
		HSLFSlideShow ppt = null ;
		try{
			FileInputStream is = new FileInputStream(file);
			ppt = new HSLFSlideShow(is);
		    is.close();
	
		    Dimension pgsize = ppt.getPageSize();
	
		    int idx = 1;
		    for (HSLFSlide slide : ppt.getSlides()) {
	
		        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
		        Graphics2D graphics = img.createGraphics();
		        // clear the drawing area
		        graphics.setPaint(Color.white);
		        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
	
		        // render
		        slide.draw(graphics);
	
		        // save the output
		        FileOutputStream out = new FileOutputStream("D:\\temp\\out\\slide-" + idx + ".png");
		        javax.imageio.ImageIO.write(img, "png", out);
		        out.close();
	
		        idx++;
		    }
		}catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
	public static boolean doPPT2007toImage(File file) {
		FileInputStream is = null;
		XMLSlideShow pptx = null ;
		try {
			is = new FileInputStream(file);
			pptx = new XMLSlideShow(is);
			is.close();
	
		    Dimension pgsize = pptx.getPageSize();
	
		    int idx = 1;
		    for (XSLFSlide slide : pptx.getSlides()) {
		    	//List<XSLFShape> shapes = slide.getShapes();
		    	
		        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
		        Graphics2D graphics = img.createGraphics();
		        // clear the drawing area
		        graphics.setPaint(Color.white);
		        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
	
		        // render
		        slide.draw(graphics);
		        
		        // save the output
		        FileOutputStream out = new FileOutputStream("D:\\temp\\out\\slide-" + idx + ".png");
		        javax.imageio.ImageIO.write(img, "png", out);
		        out.close();
	
		        idx++;
		    }
		}catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

}
